#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <memory>

#include "TcpSever.hpp"
#include "Logger.hpp"
#include "Common.hpp"
#include "Protocol.hpp"
#include "Caculate.hpp"

using cal_fun = std::function<Response(Request &)>;
class Parse
{
public:
    Parse(cal_fun c)
        : _cal(c)
    {
    }
    std::string Hander(std::string &package)
    {
        //解析
        std::string content;
        std::string result;
        while(Decode(package, &content))
        {         
            LOG(LogLevel::DEBUG) << "content# " << content;   
            if(content.empty()) break;

            Request request;
            // 反序列化
            if(!request.Deserialize(content))
            {
                LOG(LogLevel::ERROR) << "反序列化失败!";
               break;
            }
            // 计算
            Response response = _cal(request);

            std::string res;
            // 序列化
            response.Serialize(res);
            // 编码
            Encode(res);    
            result += res;
        }

        // 发送
        LOG(LogLevel::DEBUG) << "result# " << result;
        return result;
    }

private:
    cal_fun _cal;
};

int main()
{
    //计算模块
    Caculate cal;
    //解析模块
    Parse parse([&cal](Request &request) {
        return cal.Excute(request);
    });
    std::unique_ptr<TcpSever> sev_ptr = std::make_unique<TcpSever>([&parse]
        (std::string &package) { return parse.Hander(package); });
    sev_ptr->SeverInit();
    sev_ptr->Start();
    return 0;
}